package com.base.look.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.commonlib.sp.SpUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.look.R;
import com.base.look.act.LookBigImagesActivity;
import com.base.look.bean.CommentModel;
import com.base.look.bean.ImageUrl;
import com.base.look.bean.LookListBean;
import com.base.look.utils.TimeUtils;
import com.base.look.widget.MultiImageView;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zw on 2020/3/2.
 * 看看列表适配器
 */

public class LookAdapter extends RecyclerView.Adapter<LookAdapter.ViewHolder> {
    private Context mContext;
    private OnActionListener mOnActionListener;
    private List<LookListBean.Rows> mData;

    public LookAdapter(Context mContext, List<LookListBean.Rows> mData) {
        this.mContext = mContext;
        this.mData = mData;
    }

    public void setOnActionListener(OnActionListener listener) {
        mOnActionListener = listener;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_video_comment_item, parent, false);
        return new ViewHolder(view);
    }


    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final LookListBean.Rows rows = mData.get(position);

        holder.icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onUserIconClick(rows.getPublisher());
            }
        });

        holder.name.setText(rows.getPublisher());
        try {
            holder.time.setText(TimeUtils.format(rows.getPublishTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }


        holder.commentCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onComment(rows, position);
            }
        });


        holder.zanCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnActionListener != null) {
                    mOnActionListener.onHit(rows, position);
                }
            }
        });

        String content = rows.getContent();
        if (content.length() > 100) {
            SpannableStringBuilder contentSb = new SpannableStringBuilder();
            contentSb.append(content.substring(0, 30)).append("...");
            String firstStr = "全文";
            SpannableStringBuilder firstSsb = new SpannableStringBuilder(firstStr);
            firstSsb.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    if (mOnActionListener != null) {

                        //mOnActionListener.onDetailClick(rows.getComments().get(position));
                    }

                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(ContextCompat.getColor(mContext, R.color.colorAccent));
                    ds.setUnderlineText(false);
                }
            }, 0, firstStr.length(), 0);
            contentSb.append(firstSsb);
            holder.content.setText(contentSb);
        } else {
            holder.content.setText(content);
        }


//        holder.view.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mOnActionListener != null) {
//                    Log.e("ffffffff","==========================1111");
//                    //LookListBean.Rows.Comments comments,LookListBean.Rows rows,int position
//                    mOnActionListener.onDetailClick(rows.getComments().get(0),rows,position);
//                   // mOnActionListener.onDetailClick(rows.getComments().get(0));
//                }
//
//            }
//        });


        holder.view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mOnActionListener != null)
                    mOnActionListener.onLongClick(rows);
                return true;
            }
        });

        refreshItemView(holder, rows, position);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            //局部刷新，
            Object object = payloads.get(0);
            if (object instanceof CommentModel) {
                refreshItemView(holder, mData.get(position), position);

            }
        }
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }


    private void refreshItemView(ViewHolder holder, final LookListBean.Rows rows, final int position) {
        //得到drawable对象，即所要插入的图片
        Drawable d;
        if (rows.getThumbIdList() != null && rows.getThumbList() != null) {
            for (int i = 0; i < rows.getThumbIdList().size(); i++) {
                if (rows.getThumbIdList().get(i).equals(SpUtil.getString("userId"))) {
                    rows.setHit(true);
                } else {
                    rows.setHit(false);
                }
            }
        } else {
            rows.setHit(false);
        }
        if (rows.isHit()) {
            d = mContext.getResources().getDrawable(R.mipmap.icon_zan);
        } else {
            d = mContext.getResources().getDrawable(R.mipmap.icon_un_zan);
        }
        holder.zanCount.setCompoundDrawablesWithIntrinsicBounds(d,
                null, null, null);
        holder.zanCount.setCompoundDrawablePadding(mContext.getResources().getDimensionPixelOffset(R.dimen.dp_4));
        if (rows.getThumbList().size() > 0 || rows.getThumbIdList().size() > 0) {
            holder.item_line.setVisibility(View.VISIBLE);

        } else {
            holder.item_line.setVisibility(View.GONE);
        }
        if (rows.getComments().size() > 0 || rows.getThumbList().size() > 0) {
            holder.item_thumbs_lin.setVisibility(View.VISIBLE);
        } else {
            holder.item_thumbs_lin.setVisibility(View.GONE);
        }

        //holder.zanCount.setText(String.valueOf(rows.getThumbCount()));
        holder.zanCount.setText("赞");
        //回复
        //holder.commentCount.setText(String.valueOf(rows.getComments().size()));
        holder.commentCount.setText("评论");


        if (rows.getThumbList().size() > 0) {
            String s = rows.getThumbList().toString();
            s = s.replaceAll("\\[", "");
            s = s.replaceAll("\\]", "");
            holder.item_tv_thumbs.setText(s);
            holder.item_tv_thumbs.setVisibility(View.VISIBLE);
        } else {
            holder.item_tv_thumbs.setVisibility(View.GONE);
        }
        final List<String> imagesArray = new ArrayList<>();
        if (rows.getFiles() != null) {
            try {
                JSONArray jsonArray = new JSONArray(rows.getFiles());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    imagesArray.add(jsonObject.getString("url"));     //解析获得 url
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        holder.multiImageView.setList(imagesArray);

        holder.multiImageView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ImageUrl imageUrl = new ImageUrl();
                imageUrl.setUrlList(imagesArray);
                Gson gson = new Gson();
                String url = gson.toJson(imageUrl);
                Intent intent = new Intent(mContext, LookBigImagesActivity.class);
                intent.putExtra("url", url);
                intent.putExtra("position", position);
                mContext.startActivity(intent);
//                ARouter.getInstance().build("/look/images").withString("url", url)
//                        .withInt("position", position)
//                        .navigation();
            }
        });
        //第一级的时候会有评论的回复内容，需展示
        final List<LookListBean.Rows.Comments> replays = rows.getComments();
        if (replays != null && replays.size() > 0) {
            holder.contentReply.setVisibility(View.VISIBLE);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            for (int i = 0; i < replays.size(); i++) {
                final LookListBean.Rows.Comments replay = replays.get(i);
                SpannableStringBuilder ssb = new SpannableStringBuilder();
                String posterName = replay.getFromName();
                // 发表评论的人名长度
                int posterNameLength = 0;
                if (!TextUtils.isEmpty(replay.getFromName())) {
                    posterNameLength = posterName.length();
                    //把评论发送者名字添加进去             
                    ssb.append(posterName);
                } else {
                    //posterName = rows.getPublisher();
                    posterName = "匿名";
                    posterNameLength = posterName.length();
                    //把评论发送者名字添加进去
                    ssb.append(posterName);
                }
                //ssb.setSpan(new ForegroundColorSpan(Color.RED), 0, posterNameLength, 0);

                final String finalPosterName = posterName;
//                ssb.setSpan(new ClickableSpan() {
//
//                    @Override
//                    public void onClick(View widget) {
//                        if (mOnActionListener != null) {
//                            mOnActionListener.onDetailClick(replay, rows, position);
//                        }
//
//                    }
//
//                    @Override
//                    public void updateDrawState(TextPaint ds) {
//                        // TODO Auto-generated method stub
//                        super.updateDrawState(ds);
//                        ds.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
//                        ds.setUnderlineText(false);
//                    }
//                }, 0, posterNameLength, 0);

//                ssb.setSpan(new ClickableSpan() {
//
//                                @Override
//                                public void updateDrawState(TextPaint ds) {
//                                    // TODO Auto-generated method stub
//                                    super.updateDrawState(ds);
//                                    ds.setUnderlineText(false);
//                                }
//
//                                @Override
//                                public void onClick(View widget) {
//                                    Log.e("ff",replay.toString());
//                                    mOnActionListener.onDetailClick(replay, rows, position);
//                                }
//                            }, 0,
//                        ssb.length(),
//                        Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                holder.contentReply.setMovementMethod(LinkMovementMethod.getInstance());//触发点击事件
                if (replay.getType() == 1) {
                    String reply = " " + mContext.getString(R.string.recover) + " ";
                    //添加“回复”二字
                    ssb.append(reply);
                    ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.grey)),
                            posterNameLength, reply.length() + posterNameLength, 0);
                    //把被回复的名字添加进去
                    final String replyName;
                    if (TextUtils.isEmpty(replay.getToName())) {
                        replyName = "未知名称";
                    } else {
                        replyName = replay.getToName();
                    }
                    if (!TextUtils.isEmpty(replyName)) {
                        ssb.append(replyName);
                    }
                    ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorPrimary)),
                            reply.length() + posterNameLength, reply.length() + posterNameLength + replyName.length(), 0);
//                    ssb.setSpan(new ClickableSpan() {
//
//                        @Override
//                        public void onClick(View widget) {
//                            if (mOnActionListener != null) {
//                                mOnActionListener.onDetailClick(replay, rows, position);
//                            }
//
//                        }
//
//                        @Override
//                        public void updateDrawState(TextPaint ds) {
//                            super.updateDrawState(ds);
//                            ds.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
//                            ds.setUnderlineText(false);
//                        }
//                    }, reply.length() + posterNameLength, reply.length() + posterNameLength + replyName.length(), 0);


//                    ssb.setSpan(new ClickableSpan() {
//
//                                    @Override
//                                    public void updateDrawState(TextPaint ds) {
//                                        // TODO Auto-generated method stub
//                                        super.updateDrawState(ds);
//                                        ds.setUnderlineText(false);
//                                    }
//
//                                    @Override
//                                    public void onClick(View widget) {
//                                        mOnActionListener.onDetailClick(replay, rows, position);
//                                    }
//                                }, 0,
//                            ssb.length(),
//                            0);
                }

                //内容
                ssb.append(": ");
                int wordsLength = replay.getContent().length();
                Log.e("ff   ", ssb.toString());
                SpannableString sbContent = new SpannableString(replay.getContent());
                sbContent.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.text_5e)),
                        0, wordsLength, 0);
                ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.colorPrimary)),
                        0, wordsLength, 0);
                ssb.append(sbContent);
                                    ssb.setSpan(new ClickableSpan() {

                                    @Override
                                    public void updateDrawState(TextPaint ds) {
                                        // TODO Auto-generated method stub
                                        super.updateDrawState(ds);
                                        ds.setUnderlineText(false);
                                    }

                                    @Override
                                    public void onClick(View widget) {
                                        Log.e("ff",replay.toString());
                                        mOnActionListener.onDetailClick(replay, rows, position);
                                    }
                                }, 0,
                                            wordsLength,
                            0);
                builder.append(ssb);
                if (i != replays.size() - 1)
                    builder.append("\n");
            }
            //如果回复数量大于返回显示的数量，则显示"展开**条回复"
            if (0 > replays.size()) {
                builder.append("\n");
                SpannableStringBuilder ssb = new SpannableStringBuilder();
                String more = "展开" + rows.getThumbCount() + "条回复";
                ssb.append(more);
//                ssb.setSpan(new ClickableSpan() {
//
//                    @Override
//                    public void onClick(View widget) {
//                        if (mOnActionListener != null) {
//                            // mOnActionListener.onDetailClick(replay,rows,position);
//
//                        }
//                    }
//
//                    @Override
//                    public void updateDrawState(TextPaint ds) {
//                        // TODO Auto-generated method stub
//                        super.updateDrawState(ds);
//                        ds.setColor(ContextCompat.getColor(mContext, R.color.colorAccent));
//                        ds.setUnderlineText(false);
//                    }
//                }, 0, more.length(), 0);
                builder.append(ssb);
            }
            holder.contentReply.setText(builder);
        } else {
            holder.contentReply.setVisibility(View.GONE);
        }
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView icon;
        TextView name;
        TextView time;
        TextView item_tv_thumbs;
        TextView commentCount, zanCount;
        TextView content;
        View item_line;
        LinearLayout item_thumbs_lin;
        TextView contentReply;
        MultiImageView multiImageView;
        View view;
        RecyclerView recyclerView;

        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            icon = itemView.findViewById(R.id.item_icon);
            name = itemView.findViewById(R.id.item_name);
            time = itemView.findViewById(R.id.item_time);
            recyclerView = itemView.findViewById(R.id.recycler_iamges);
            commentCount = itemView.findViewById(R.id.item_comment);
            item_thumbs_lin = itemView.findViewById(R.id.item_thumbs_lin);
            item_line = itemView.findViewById(R.id.item_line);
            zanCount = itemView.findViewById(R.id.item_zan);
            item_tv_thumbs = itemView.findViewById(R.id.item_tv_thumbs);
            content = itemView.findViewById(R.id.item_content);
            multiImageView = itemView.findViewById(R.id.multi_image);
            contentReply = itemView.findViewById(R.id.item_content_reply);
        }
    }


    public interface OnActionListener {
        void onComment(LookListBean.Rows item, int position);

        void onHit(LookListBean.Rows item, int position);

        void onDetailClick(LookListBean.Rows.Comments comments, LookListBean.Rows rows, int position);

        void onAllReplyOpen(LookListBean.Rows item);

        void onUserIconClick(String userName);

        void onLongClick(LookListBean.Rows item);
    }
}
